import { PureComponent } from 'react';
import { Menu,Item,contextMenu } from 'react-contexify';
import { getNodeByKeyAndCallbackProcess } from '@/components/_utils/algorithmTools';
import '@/assets/iconfont/iconfont';
import {
	Tree,
  	Input,
	Icon,
	Button,
} from 'antd';
const { Search } = Input;
const { TreeNode } = Tree;
import 'react-contexify/dist/ReactContexify.min.css';
import styles from './ProDictionarysList.less';

class MenuAuthTree extends PureComponent {
	state = {
	    expandedKeys: [],
	    autoExpandParent: true,
	    checkedKeys: [],
	    selectedKeys: [],
	    defaultExpandedKeys: [],
	    selectedTreeByRightClick:"",
	    searchValue: '',
	    dataList: [],
	    sourceTreeNodeId:"",
	    treeData: [],
	    display:"block",
	};
	
	
	constructor(props) {
		super(props);
	}
	
 	componentDidMount() {
 		
    	this.onExpand(['000000000000']); // 手动触发，否则会遇到第一次不展开的Bug

  	}
 	
	componentWillReceiveProps(nextProps) {
		if(undefined != nextProps.checkedKeys && nextProps.checkedKeys.list !== this.props.checkedKeys.list) {
	      this.setState({checkedKeys: nextProps.checkedKeys.list});
		}
		
		if(undefined != nextProps.menu && nextProps.menu.list !== this.props.menu.list) {
	      this.setState({treeData: nextProps.menu.list});
		}
	}
	
//展开收起
	onExpand = expandedKeys => {
	    this.setState({
	      expandedKeys,
	      autoExpandParent: false,
	    });
	};
  
  	onCheck = (checkedKeys,info) => {
	  	const { checkedTreeChild } = this.props;
	  	checkedTreeChild(info);
	    this.setState({ checkedKeys });
  	};
  	
  	onSelect = (selectedKeys, { node }) => {
    	const { checkedTreeChild } = this.props;
    	this.setState({ selectedKeys });
	   	checkedTreeChild(node);
  	};
    	
  	addMenuTreeNode = () => {
  		const { handleModalVisible } = this.props;
	    handleModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	updateMenuTreeNode = () => {
  		const { handleUpdateModalVisible } = this.props;
	    handleUpdateModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	viewMenuTreeNode = () => {
  		const { handleViewModalVisible } = this.props;
	    handleViewModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	deleteMenuTreeNode = () => {
  		const { handleDeleteRecord } = this.props;
	    handleDeleteRecord(this.state.selectedTreeByRightClick);
	};
	
	
	RithtClickTreeNode = ({event,node}) => {
		event.preventDefault();
		contextMenu.show({
	      id: 'menu_id',
	      event: event,
	      props: {
	        foo: 'bar'
	      }
	    });

	    if(node.props.dataRef.key != '000000000000') {
	  		this.setState({ 
				selectedTreeByRightClick: node.props.dataRef,
				display:"block",
			});
	  	}else {
	  		this.setState({ 
				selectedTreeByRightClick: node.props.dataRef,
				display:"none",
			});
	  	}
	}
	
	MyAwesomeMenu = () => (
		<Menu id='menu_id' theme="light" style={{zIndex: 1000}}>
	       {/*<Item onClick={this.addMenuTreeNode}>
	       		<Icon type="plus-circle" style={{fontSize: 16,paddingTop: 3}}/>
	       		<span style={{paddingLeft: 10}}>新增</span>
	       </Item>*/}
	       <Item onClick={this.updateMenuTreeNode} style={{display: this.state.display}}>
		       <Icon type="edit" style={{fontSize: 16,paddingTop: 3}}/>
		       <span style={{paddingLeft: 10}}>修改</span>
	       </Item>
	       <Item onClick={this.deleteMenuTreeNode} style={{display: this.state.display}}>
	       		<Icon type="delete" style={{fontSize: 16,paddingTop: 3}}/>
	       		<span style={{paddingLeft: 10}}>删除</span>
	       	</Item>
	    </Menu>
	);
	
//	onChange = e => {
//		const { menu: { list } } = this.props;
//	    const { value } = e.target;
//	    const expandedKeys = this.state.dataList
//	      .map(item => {
//	        if (item.title.indexOf(value) > -1) {
//	          return this.getParentKey(item.title, list);
//	        }
//	        return null;
//	      }).filter((item, i, self) => item && self.indexOf(item) === i);
//	    this.setState({
//	      expandedKeys,
//	      searchValue: value,
//	      autoExpandParent: true,
//	    });
//	};
	
	getParentKey = (title, tree) => {
	  let parentKey;
	  for (let i = 0; i < tree.length; i++) {
	    const node = tree[i];
	    if (node.children) {
	      if (node.children.some(item => item.title === title)) {
	        parentKey = node.key;
	      } else if (this.getParentKey(title, node.children)) {
	        parentKey = this.getParentKey(title, node.children);
	      }
	    }
	  }
	  return parentKey;
	};
	

	generateList = data => {

	  if( undefined == data ){ return false;}

	  for (let i = 0; i < data.length; i++) {
	    const node = data[i];
	    const { key,title } = node;
	    this.state.dataList.push({ key, title: title });
	    if (node.children) {
	      this.generateList(node.children);
	    }
	  }
	};
	
//	renderTreeNodes = data => {
//
//	  if( undefined == data ){ return false;}
//
//		
//	   return data.map(item => {
//		    const index = item.title.indexOf(this.state.searchValue);
//	        const beforeStr = item.title.substr(0, index);
//	        const afterStr = item.title.substr(index + this.state.searchValue.length);
//	        const title =
//	          index > -1 ? (
//	            <span onMouseOver={() => this.mouseOver(item)}>
//	              {beforeStr}
//	              <span style={{ color: '#f50' }}>{this.state.searchValue}</span>
//	              {afterStr}
//	            </span>
//	          ) : null;
//	          
//		      if (item.children) {
//		        return (
//		    	    <TreeNode title={title} key={item.key} dataRef={item}>
//			            {this.renderTreeNodes(item.children)}
//			         </TreeNode>
//		        );
//		      }
//		      if(index > -1) {
//		      		return <TreeNode {...item} dataRef={item} title={title} key={item.key}/>;
//		      }else {
//					return <TreeNode {...item} dataRef={item} title={title} key={item.key} style={{display: 'none'}}/>;
//		      }
//	  	});
//	} 	
	
	
	renderTreeNodes = data => {

	  if( undefined == data ){ return false;}

		
	   	return data.map(item => {
	   		
	        const title = (
	            <span onMouseOver={() => this.mouseOver(item)}>{item.title}</span>
	        )
	          
		    if (item.children) {
		        return (
		    	    <TreeNode title={title} key={item.key} dataRef={item}>
			            {this.renderTreeNodes(item.children)}
			         </TreeNode>
		        );
		    }
			return <TreeNode {...item} dataRef={item} title={title} key={item.key}/>;
	  	});
	} 
	
	
	onSearch = value => {
		const { dispatch } = this.props;
		dispatch({
	        type: 'prodictionarys/get_all_for_prodictionarys_type',
	        payload:{
	        	description: value,
	        },
	        callback: (response) => {
	        	
	        }
	  	});
	};
	
	mouseOver = (ele) => {
		contextMenu.show({
	      id: 'menu_id',
	      event: event,
	      props: {
	        foo: 'bar'
	      }
	    });
	    
	    this.setState({ 
			selectedTreeByRightClick: ele,
		});
	    
	}
	
	onDrop = async ({event, node, dragNode, dragNodesKeys}) => {

		const levelcode = node.props.dataRef.levelcode;
		const dropKey = node.props.eventKey;
		const dragKey = dragNode.props.eventKey;
		const dragKey_parent_id = dragNode.props.dataRef.parentid;
		const new_levelcode = levelcode+"/"+dragKey;


		const data = [...this.state.treeData];


	   	let dragObj;

	   	getNodeByKeyAndCallbackProcess(data, dragKey,(item, index, arr) => {
	      arr.splice(index, 1);
	      dragObj = item;
	    });
	    
		//测试拖拽时候使用
	   /*getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {

	        item.children = item.children || [];
	        // where to insert 示例添加到尾部，可以是随意位置
	        item.children.push(dragObj);
	   });*/


		const { dispatch } = this.props;
		const levecode = this.state.targetTreeLevelCode + "/" + dragNode.props.id;
		await dispatch({
	        type: 'promenuauth/update_change_target_node_with_source_node',
	        payload:{
	        	source_parentid: dragKey_parent_id,
	        	source_id: dragKey,
	        	target_id: dropKey,
	        	levelcode: new_levelcode,
	        },
	        callback: (response) => {
	                 //持久化变拖拽时候使用
				    getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {
				        item.children = item.children || [];
				        // where to insert 示例添加到尾部，可以是随意位置
				        item.children.push(response.datarecord||{});
				    });
	        }
	  	});


	   await this.setState({
      		treeData: data,
       });

	  
	}

  render() {
  	const { menu: { list } } = this.props;
  	
		const { autoExpandParent,expandedKeys,selectedKeys,checkedKeys,treeData } = this.state;
	
//		this.generateList(list);
	    return (
	    	<div>
	    		<div>
	    			<Search style={{ marginBottom: 8,width: '75%'}} placeholder="请输入类型名称" onSearch={this.onSearch} />
	    			<Button icon="plus" type="primary" style={{float: 'right',verticalAlign:'middle'}} onClick={ this.addMenuTreeNode }></Button>
				    {/*<svg className={`${styles.icon}`} style={{fontSize: '2rem',float: 'right',verticalAlign:'middle',cursor: 'pointer'}} aria-hidden="true" onClick={this.addMenuTreeNode}>
						<use xlinkHref="#icon-jiahao"></use>
			  		</svg>*/}
	    		</div>
				<div className={styles.typeScrollbar} style={{maxHeight:'500px',overflow:'auto'}}>
					<Tree
			        onExpand={this.onExpand}
			        expandedKeys={expandedKeys}
			        autoExpandParent={autoExpandParent}
			        onCheck={this.onCheck}
			        checkedKeys={checkedKeys}
			        onSelect={this.onSelect}
			        selectedKeys={selectedKeys}
			        onRightClick={this.RithtClickTreeNode}
			        draggable
			        onDrop={this.onDrop}
			        style={{marginLeft: '-24px'}}
			        >
			      		 {this.renderTreeNodes(treeData)}
			      </Tree>
				</div>
			      {this.MyAwesomeMenu()}
	    	</div>
	    )
  }
 }

export default MenuAuthTree;